package com.zds.passwordbox.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.zds.passwordbox.NormalAccountActivity;
import com.zds.passwordbox.R;
import com.zds.passwordbox.adapter.NormalAccountAdapter;
import com.zds.passwordbox.common.Constant;
import com.zds.passwordbox.data.dao.AccountDao;
import com.zds.passwordbox.data.dao.domain.UserAccount;

import java.util.LinkedList;

public class AccountFragment extends Fragment {
    private final static String TAG = "AccountFragment";
    private final AccountDao accountDao;

    private Toolbar toolbar;

    private SmartRefreshLayout swipeRefreshLayout;

    private NormalAccountAdapter adapter;

    private LinkedList<UserAccount> dataList = new LinkedList<>();

    private ActivityResultLauncher<Intent> accountDetailLauncher;

    public AccountFragment(AccountDao accountDao) {
        this.accountDao = accountDao;
    }

    private boolean isImport = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 设置支持ToolBar
        View view = inflater.inflate(R.layout.account_fragment, container, false);
        toolbar = requireActivity().findViewById(R.id.my_toolbar);
        ((AppCompatActivity) requireActivity()).setSupportActionBar(toolbar);
        setHasOptionsMenu(true);
        // 设置ListView
        initListView(requireContext(), view);
        swipeRefreshLayout = view.findViewById(R.id.account_list_refresh);
        // 设置下拉刷新监听器
        swipeRefreshLayout.setOnRefreshListener((RefreshLayout refreshLayout) -> {
            refresh(null);
            // 停止刷新动画
            swipeRefreshLayout.finishRefresh();
        });
        accountDetailLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                this::handleActivityResult);

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isImport) {
//            refresh(null);
            swipeRefreshLayout.autoRefresh();
            Log.d(TAG, "onResume autoRefresh ");
            isImport = false;
        }
    }


    public boolean isImport() {
        return isImport;
    }

    public void setImport(boolean anImport) {
        isImport = anImport;
    }

    private void refresh(String newText) {
        if (adapter != null) {
            this.dataList.clear();
            this.dataList.addAll(accountDao.queryList(0, newText));
            adapter.notifyDataSetChanged();
            Log.d(TAG, "adapter notify success !!! ");
        } else {
            Log.d(TAG, "adapter is null ");
        }
    }

    private void initListView(Context context, View view) {
        ListView listView = view.findViewById(R.id.account_list);
        // 获取账户列表
        this.dataList = accountDao.queryList(0, null);
        adapter = new NormalAccountAdapter(dataList, context);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((parent, view1, position, id) -> {
            Intent intent = new Intent(getActivity(), NormalAccountActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt("actionType", Constant.NORMAL);
            bundle.putLong("id", id);
            intent.putExtras(bundle);
            accountDetailLauncher.launch(intent);
        });
        listView.setOnItemLongClickListener((parent, view2, position, id) -> {
            new AlertDialog.Builder(getActivity()).setTitle("是否删除此账户？")
                    .setPositiveButton("确定", (dialog, id1) -> {
                        accountDao.delete(id);
                        refresh(null);
                    })
                    .setNegativeButton("取消", ((dialog, which) -> dialog.dismiss()))
                    .show();
            // 返回true表示已经处理了该事件
            return true;
        });
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        toolbar.setTitle(R.string.tab_account);
        //找到searchView
        inflater.inflate(R.menu.account_menus, menu);
        MenuItem item = menu.findItem(R.id.add_btn);
        if (item != null) {
            item.setOnMenuItemClickListener(item1 -> {
                Intent intent = new Intent(getActivity(), NormalAccountActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt("actionType", Constant.INSERT);
                bundle.putLong("id", -1);
                intent.putExtras(bundle);
                accountDetailLauncher.launch(intent);
                return true;
            });
        }
        MenuItem searchItem = menu.findItem(R.id.account_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        if (searchView != null) {
            searchView.setQueryHint("请输入账户类型搜索");
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    // 根据输入的内容更新dataList
                    refresh(newText);
                    return true;
                }
            });
            // 直接使用searchView的onCloseListener在高版本的andorid是不起作用的,
            // searchView中的X其实就是id为R.id.search_close_btn的ImageView
            // ImageView imageView = searchView.findViewById(androidx.appcompat.R.id.search_close_btn);
            // imageView.setOnClickListener(v -> {
            //     // 清楚搜索框数据并重新加载列表数据
            //     searchView.clearFocus();
            //     queryList(null);
            //     adapter.notifyDataSetChanged();
            // });
        }
    }

    private void handleActivityResult(ActivityResult result) {
        if (result.getResultCode() == Activity.RESULT_OK && result.getData()!= null) {
            // 当SecondActivity返回RESULT_OK时执行的操作
            int type = result.getData().getIntExtra("handleType", 0);
            // 如果是新增或者是编辑，刷新列表内容
            if (type == 1 || type == 2) {
                refresh(null);
            }
        }
    }
}
